package db

import (
	"fmt"
	"github.com/go-redis/redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

var (
	MySqlDB *gorm.DB
	RedisDB *redis.Client
)

func InitMySql() *gorm.DB {
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		log.Panicln("初始化MySQL异常:", err)
	}

	MySqlDB = db
	log.Println("-----------------数据库初始化完毕-----------------")
	return db
}

func InitRedis() *redis.Client {
	rdb := redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.host") + ":" + viper.GetString("redis.port"),
		Password: viper.GetString("redis.password"),
		DB:       0,
	})

	RedisDB = rdb
	log.Println("-----------------Redis初始化完毕-----------------")
	return rdb
}

func GetMysql() *gorm.DB {
	return MySqlDB
}

func GetRedis() *redis.Client {
	return RedisDB
}
